// 并发任务
class TaskQueue {
    constructor(maxNum) {
        this.maxNum = maxNum
        this.running = 0
        this.quene = []
        this.results = []
    }

    addTask(task) {
        return new Promise((resolve, reject) => {
            this.quene.push({
                task,
                resolve,
                reject
            })
            this.next()
        })
    }

    next() {
        while(this.running < this.maxNum && this.quene.length) {
            const { task, resolve, reject } = this.quene.shift()
            task().then(res => {
                resolve(res)
            }).catch((err) => {
                reject(err)
            }).finally(() => {
                this.running--
                this.next()
            })
            this.running++
        }
    }
}

function startLimit() {
    const quene = new TaskQueue(2)
    
    function timeouter(timer) {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(timer)
            }, timer)
        })
    }
    
    quene.addTask(() => timeouter(3000)).then(res => {
        console.log(res)
    })
    quene.addTask(() => timeouter(3000)).then(res => {
        console.log(res)
    })
    quene.addTask(() => timeouter(2000)).then(res => {
        console.log(res)
    })
    quene.addTask(() => timeouter(3000)).then(res => {
        console.log(res)
    })
}
